package com.zzptc.myapp1130bookreader.Utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.Charset;

public class ProcessText {



    public  long pages;   //总页数
    public  final int SIZE=3000;  //每页字节数 字节数固定 3000=编码
    public  long  bytescount;  //字节总数
    public  long  currentpage;   // 当前页码
    public RandomAccessFile readFile;

    public ProcessText(File file,long currentpage) {

        try {
            readFile= new RandomAccessFile(file,"r");//实例化控件 //ait+回车=catch
            bytescount=readFile.length(); //ait+回车=catch
            pages=bytescount/SIZE; //字节总数除以字节数
            this.currentpage=currentpage;//传入页码

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void seek(long page){ //寻找页面
        try {
            readFile.seek(page*SIZE); //ait+回车=catch
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    private String read(){  //读字节数

        byte[]buffer=new byte[SIZE+8];//内容防止重叠//加8个字节数或者16个字节数（最多16个字节)

        try {
            readFile.read(buffer);//buffer=3000字节数 ait+回车=catch
        } catch (IOException e) {
            e.printStackTrace();

        }
        String str=new String(buffer, Charset.forName("utf-8"));//转化字节为utf-8格式
        str=str.replace("�","");//转化？为字节体

        return  str; //闭合这个方法

    }


    public String getPre(){ //获取上一页的页面
        String content=null; //先定义一个Str类型

        if (currentpage<=1){ //从第一页开始读，是从0开始的
            seek(0);
            content=read();
            currentpage=1;//这是当前页面数  0/1 关系不大
        }else {
            seek(currentpage-2);
            content=read();
            currentpage--;
        }
        return content; //闭合这个方法

    }
    public String getNext(){ //读取下一页
        String content=null;
        if (currentpage>=pages){
            currentpage=pages;
            seek(currentpage);
            content=read();
        }else {
            seek(currentpage);
            content=read();
            currentpage++;
        }
        return content; //闭合这个方法
    }
    public String getAppoint(long appointpage){
        String content = null;
        currentpage=appointpage;
        seek(appointpage-1);
        content=read();
        return content;
    }
}
